



********************************************************************************
********************************************************************************
***************** APPENDIX FIGURES AND TABLES **********************************
********************************************************************************
********************************************************************************
cap mkdir `"$output/log"'
cap mkdir `"$output/log/appendix"'
cap mkdir `"$output/medicaid_treat_pattern"'

cap log close 
log using `"$output/log/appendix/appendix.smcl"', replace

di "This run uses code version from 2023/03/29"

********************************************************************************
********************************************************************************
********************************* Table A3 *************************************
********************************************************************************
********************************************************************************
use  `"$output/temp/estimation_data_bin.dta"', clear

di "The following numbers are for all groups'"
gen continuation = .99*V_S+.99*0.5772156649
replace continuation = 0 if n_S ==.
bys visit_billing_id: egen max_cont = max(continuation)
gen resub = choice_S*(n_S!=.) // =1 if resubmitted AND non-empty
bys visit_billing_id: egen claim_resub = max(resub)
bys visit_billing_id : gen nnn = _n 

tab claim_resub pay_type_pooled_st if nnn==1, sum(max_cont) nofr nost

foreach p in "Medicare" "Medicaid" "Commercial" {
	
	preserve
	keep if pay_type_pooled_st	== "`p'"

	estpost tabstat max_cont if nnn==1, by(claim_resub) stat(mean) columns(statistics) nototal
	estimates save `"$output/model_exhibits/maxcont_`p'.ster"', replace 
	restore
	
	est use `"$output/model_exhibits/maxcont_`p'.ster"' 
	eststo maxcont_`p'
	
}

#delimit ;
	esttab maxcont_Medicaid maxcont_Medicare maxcont_Commercial 
		using `"$output/model_exhibits/tablea1_panela.tex"',cells("mean(fmt(2))") 
		noobs collabels(none) mtitles("Medicaid" "Medicare" "Commercial") 
		unstack nonumbers booktabs replace substitute(_ \_) 
		coeflabels(0 "Instances in which providers do not resubmit claims" 
				   1 "Instances in which providers resubmit claims");
#delimit cr


foreach p in "Medicare" "Medicaid" "Commercial" {
	
	preserve
	keep if pay_type_pooled_st	== "`p'"

	estpost tabstat continuation if n_S!=., by(choice_S) stat(mean) columns(statistics) nototal
	estimates save `"$output/model_exhibits/cont_`p'.ster"', replace 
	restore
	
	est use `"$output/model_exhibits/cont_`p'.ster"' 
	eststo cont_`p'
	
}

#delimit ;
	esttab cont_Medicaid cont_Medicare cont_Commercial 
		using `"$output/model_exhibits/tablea1_panelb.tex"' ,cells("mean(fmt(2))") 
		noobs collabels(none) mtitles("Medicaid" "Medicare" "Commercial") 
		unstack nonumbers booktabs replace substitute(_ \_) 
		coeflabels(0 "Not resubmitted set of line items" 
				   1 "Resubmitted set of line items");
#delimit cr
	

cd `"$output/model_exhibits"'
	
//Combine the tables into one tables with three panels 
cap prog drop panelcombine
prog define panelcombine
qui {
syntax, use(str asis) paneltitles(str asis) columncount(integer) save(str asis) [CLEANup]
preserve

tokenize `"`paneltitles'"'
//read in loop
local num 1
while "``num''"~="" {
local panel`num'title="``num''"
local num=`num'+1
}


tokenize `use'
//read in loop
local num 1
while "``num''"~="" {
tempfile temp`num'
insheet using "``num''", clear
save `temp`num''
local max = `num'
local num=`num'+1
}

//conditional processing loop
local num 1
while "``num''"~="" {
local panellabel : word `num' of `c(alpha)'
use `temp`num'', clear
	if `num'==1 { //process first panel -- clip bottom
	drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
	drop if v1=="\end{tabular}" | v1=="}"
	replace v1 = "\multicolumn{`columncount'}{c}{\textbf{Panel `panellabel': `panel1title'}}  \vspace{3pt} \\" if v1=="\midrule" & _n<8
	replace v1 = "" if v1=="\bottomrule" & _n>4 //this is intended to replace the bottom double line; more robust condition probably exists
	}
	else if `num'==`max' { //process final panel -- clip top
	//process header to drop everything until first hline
	g temp = (v1 == "\midrule")
	replace temp = temp+temp[_n-1] if _n>1
	drop if temp==0
	drop temp
	
	replace v1 = " \multicolumn{`columncount'}{c}{\textbf{Panel `panellabel': `panel`num'title'}} \vspace{3pt} \\" if _n==1
	}
	
	save `temp`num'', replace
local num=`num'+1
}

use `temp1',clear
local num 2
while "``num''"~="" {
append using `temp`num''
local num=`num'+1
}

outsheet using `save', noname replace noquote


	if "`cleanup'"!="" { //erasure loop
	tokenize `use'
	local num 1
		while "``num''"~="" {
		erase "``num''"
		local num=`num'+1
		}
	}

restore
}
end


panelcombine, use(tablea1_panela.tex tablea1_panelb.tex)  columncount(4) ///
	paneltitles("Maximum Continuation Value of Claims" ///
				"Continuation Value of Resubmission") ///
	save(`"../paper_inputs/table_a1.tex"') cleanup 


cd "../../../code/main_article"









********************************************************************************
********************************************************************************
***************** DATA FOR MEDICAID ACCEPT SCATTER PLOT ************************
************************** APPENDIX FIGURE A1 **********************************
********************************************************************************
********************************************************************************


cap mkdir `"$output/log"'
cap mkdir `"$output/summary_stats"'
cap mkdir `"$output/summary_stats/medicaid_accept"'
	

use `"$output/data/$line_file"', clear


******************************************************************
******************* Calculate Medicaid Acceptance ****************
******************************************************************

//payer 
gen medicaid = 0 
gen medicaid_ffs = 0 
gen medicaid_mco = 0 
replace medicaid = 1 if pay_type_pooled == 2 


//calculate accept 
bys idw_provider_id year: gegen pys_accept_medicaid = max(medicaid)
bys idw_provider_id : gegen pys_accept_medicaid_myear = max(medicaid)

// number of visits
bys visit_billing_id : gen visitindicator = _n==1
bys idw_provider_id : gegen totvisits = total(visitindicator)

// keep one visit
keep if visitindicator==1

bys payee_state_cd : gegen accept_medicaid_myear = mean(pys_accept_medicaid_myear)

bys payee_state_cd : keep if _n == 1 

keep accept_medicaid_myear payee_state_cd 

save `"$output/summary_stats/medicaid_accept/IQVIA_medicaid_accept.dta"', replace 


use `"$raw_input/$x_state_file"', clear 


keep if year > 2012 & year < 2016

bys payee_state_cd : gegen mean_accept = mean(acceptinsurance)
bys payee_state_cd : keep if _n == 1 
keep payee_state_cd mean_accept 

save `"$output/summary_stats/medicaid_accept/SKA_medicaid_accept.dta"', replace 





********************************************************************************
********************************************************************************
****************** WITHIN GROUP ACCEPTANCE HISTOGRAMS **************************
************************** APPENDIX FIGURE A2 **********************************
********************************************************************************
********************************************************************************


use `"$raw_input/$x_state_file_regression"', clear 


gen accept_medicare = 1 if medicare == "Y"
replace accept_medicare = 0 if medicare == "N"
replace accept_medicare = . if acceptinsurance == . 
bys npimedicare_id: gegen mean_medicare = mean(accept_medicare)
gen capacity = 1 - mean_medicare

*merge in the indices 
merge m:1 payee_state_cd using `"$output/indices/fee_indices_medicaid.dta"', keepusing(pi*)
keep if _merge == 3
drop _merge 

merge m:1 payee_state_cd using `"$output/indices/CIP_indices_medicaid.dta"', keepusing(*CIP*)
keep if _merge == 3
drop _merge 


//merge controls 
merge m:1 year FIPS using `"$control_var/county_controls.dta"'
keep if _merge == 3 // all data from master file merge 
drop _merge 

destring statefips, replace  
merge m:1 year statefips using `"$control_var/control_vars_state.dta"'
keep if _merge == 3 //all data from the master file merge 
drop _merge 


*group definition - use only TIN info to connect groups
gen skaGroup3a="MDPPASTIN"+tin  if ~missing(tin)

cap drop group?
gegen group3 = group(skaGroup3a)

//generate number-of-state variable 
cap drop totstates?

sort group3 paystateid
by group3 paystateid: gen markstate=_n==1
by group3: egen totstates3=sum(markstate)
drop markstate


gen ltotdocsALL1=lnumdocs

gen kaiser=CODE3=="KAI"
drop if kaiser

cap drop MDsPerCapita
gen MDsPerCapita = tot_active_md/county_pop

foreach c of varlist veteran unempl poverty white {
	
	replace `c' = `c'/county_pop
}


unab controllist: mean_ma_pen mean_number_mediciad_elig mean_dual ///
				  mean_unins65 mean_number_medicare_elig mean_medicare_enrol 
unab year_controllist: hinsva hinscare hinscaid hcovany veteran unempl ///
					   med_hh_ince avg_hhc county_pop tot_active_md poverty white


**enusre controls are notm issingsortsort npimedicare_id YearPost
foreach var of varlist `controllist' `year_controllist' {
	
	keep if `var' != . 
}

unab health_ins_market_year: hinscaid hcovany hinscare avg_hhc mean_ma_pen ///
							 mean_number_mediciad_elig mean_dual mean_unins65 ///
							 mean_number_medicare_elig mean_medicare_enrol 
unab health_prov_year: tot_active_md MDsPerCapita
unab ses_year: unempl white county_pop veteran poverty med_hh_ince
	

gen groupind = 0 
replace groupind = 1 if group3 != . & totstates3 > 1 
sum groupind, d 



foreach group of var group3 {  
		
	else if "`group'" == "group3" {
		local cross_state_var totstates3
		local definition "MDPPAS_Tax_ID"
		local group_table "Tax ID"
		xtset group3

	}


	xtset `group'
	
	cap drop physind 
	cap drop phys_count
	cap drop group_ind
	gen group_ind = 1 if `cross_state_var'>1 & `group' != .
	gen physind = 0
	bys npimedicare_id group_ind: replace physind = 1 if _n == 1 
	replace physind = 0 if group_ind != 1
	gegen phys_count = sum(physind)
	local physcount : di %7.0f phys_count
	di `physcount'
	
	local loss_denial v_initial_den_CIP`v'
	local loss lev_CIP_FE`v'
	local loss_heck lev_CIP_FE`v'_nofe
	local fee pi_c`v'_FE_cpt_line
	
	local loss_name `loss' CIP `loss_heck' CIP 
	local fee_name `fee' Fee
	ivreghdfe acceptinsurance `fee' (`loss'=`loss_denial') `health_ins_market_year' if `cross_state_var'>1 & capacity == 0, absorb(`group') cluster(paystateid) first

	
			
	cd `"$output/paper_inputs"'
	bys payee_state_cd year `group': gegen sd_accept_`group' = sd(acceptinsurance) if e(sample)
	histogram sd_accept_`group', fraction width(0.01) xti("Medicaid Accept SD by State-Group-Year")
	gr save `"appendix_accept_hist_`group'_all_w.gph"', replace
	
	histogram sd_accept_`group' if sd_accept_`group' !=0 , ///
		fraction width(0.01) xti("Medicaid Accept SD by State-Group-Year")
	gr save `"appendix_accept_hist_`group'_w.gph"', replace

	preserve 
	
		bys npimedicare_id: keep if _n == 1 
		histogram sd_accept_`group', fraction width(0.01) xti("Medicaid Accept SD by State-Group-Year")
		gr save `"appendix_accept_hist_`group'_all.gph"', replace

		histogram sd_accept_`group' if sd_accept_`group' !=0 , ///
			fraction width(0.01) xti("Medicaid Accept SD by State-Group-Year")
		gr save `"appendix_accept_hist_`group'.gph"', replace
	
	restore 
}
		
		
		
		

		
********************************************************************************
************************ ENDOGENOUS DENIAL CONCERNS ****************************
************************ MEDICAID TREATMENT PATTERN ****************************
********** Data For Appendix Table A.2 and Appendix Figure A.3 *****************
********************************************************************************
//define locals 
local procedure_rank 1000 // number of most frequent dx/charelson group we analyse 
local max_procs = 20 // number of most frequent procedures per dx/charleson group we analyse 

clear all 


cd "../../../code/main_article"

//make sure we start a new file
cap erase `"$output/medicaid_treat_pattern/coefficients.ster"' 

******************************************
*** Create datafile to use in the loop ***
******************************************
use `"$output/data/$line_file"', clear

//we neeed diagnosis and charelson
drop if dx1_code == ""
drop if charlson == . 

// create binned charleson 
gen bin_char = charlson
replace bin_char = 3 if charlson == 4 
replace bin_char = 4 if charlson >= 5

// generate dx-charlson group
tostring bin_char, gen(bin_char_st)
gen dx_charl = dx1_code + bin_char_st

//keep only necessary variables  
keep dx1_code bin_char visit_billing_id pay_type_pooled dx_charl
save `"$output/medicaid_treat_pattern/medicaid_treat_pattern.dta"', replace


*************************************************
*** Create datafile with potential procedures ***
*************************************************
use `"$output/data/$line_file"', clear

// create binned charleson 
gen bin_char = charlson
replace bin_char = 3 if charlson == 4 
replace bin_char = 4 if charlson >= 5
 
//we neeed diagnosis and charelson
drop if dx1_code == ""
drop if charlson == . 

// generate dx-charlson group
tostring bin_char, gen(bin_char_st)
gen dx_charl = dx1_code + bin_char_st

//keep 10000 most frequent dx charleson groups
bys dx_charl: gen freq = _N
replace freq = freq*(-1)
sort freq dx_charl
gen most_freq = 0 
by freq dx_charl: replace most_freq = 1 if _n == 1 
replace most_freq = sum(most_freq)

drop if most_freq > `procedure_rank'

drop freq most_freq

//keep 20 most common procedures for each dx charleson combination 
bys dx_charl proc1: gen freq = _N
//keep if freq > 2
replace freq = freq*(-1)
sort dx_charl freq proc1
gen most_freq = 0 
by dx_charl freq proc1: replace most_freq = 1 if _n == 1 
by dx_charl: replace most_freq = sum(most_freq)
drop if most_freq > `max_procs'

// generate denial probability 
gen medicaid = 0 
replace medicaid = 1 if pay_type_pooled == 2
bys proc1 dx_charl medicaid: gegen p_ndenial = mean(Y_0)
gen p_denial = 1-p_ndenial

gen p_denial_medicaid = . 
replace p_denial_medicaid = p_denial if medicaid == 1
replace p_denial = . if medicaid == 1

bys proc1 dx_charl: gegen mean_p_denial = mean(p_denial)
bys proc1 dx_charl: gegen mean_p_denial_caid = mean(p_denial_medicaid)
replace p_denial = mean_p_denial
replace p_denial_medicaid = mean_p_denial_caid


//generate procedure ID
bys proc1 dx_charl: keep if _n == 1  
bys dx_charl: gen proc_id = _n

keep proc1 dx1_code bin_char proc_id dx_charl p_denial p_denial_medicaid

//save all potential procedures 
save `"$output/medicaid_treat_pattern/potential_procs.dta"', replace 


// max_procs must be 20 
bys dx_charl: gen procedures = _N 
bys dx_charl: keep if _n == 1 
keep dx1_code bin_char dx_charl procedures

sum procedures
assert `max_procs' == `r(max)'

// save number of procedures per dx/charleson group
save `"$output/medicaid_treat_pattern/potential_procs_number.dta"', replace 

// create dta file to store coefficients 
gen coef = . 
gen stdr = . 
keep stdr coef dx_charl
save `"$output/medicaid_treat_pattern/coefficients.dta"', replace 

// levels of dx-charleson group
levelsof dx_charl, local(dx)

****************************************
*** Combine Data and run regressions ***
****************************************

foreach d of local dx {
	
	di "dx-charlson group `d'"
	
	//use the previously created data file
	use `"$output/medicaid_treat_pattern/medicaid_treat_pattern.dta"', clear

	//keep one diagnosis code 
	keep if dx_charl == "`d'"
	
	// merge number of potential procedures to expand 
	merge m:1 dx1_code bin_char using `"$output/medicaid_treat_pattern/potential_procs_number.dta"'
	keep if _merge == 3 
	drop _merge 

	// expand observations for visits to account for potential procedures 
	bys visit_billing_id dx1_code: keep if _n == 1 
	expand procedures

	//generate procedure ID for merging 
	bys visit_billing_id dx1_code: gen proc_id = _n 

	//merge potential procedures into visits 
	merge m:1 dx1_code bin_char proc_id using `"$output/medicaid_treat_pattern/potential_procs.dta"'
	keep if _merge == 3 
	drop _merge 

	//merge the procedure that was actually perfromed in a visit 
	merge 1:1 visit_billing_id dx1_code proc1 using `"$output/data/$line_file"'
	drop if _merge == 2 
	gen administered = 0 
	replace administered = 1 if _merge == 3 
	drop _merge 

	//collapse data
	gcollapse (mean) administered, by(pay_type_pooled proc_id)

	//generate medicaid dummy
	gen medicaid = 0 
	replace medicaid = 1 if pay_type_pooled == 2 

	//generate transformerd dependent var 
	gen LHS = ln(administered) - ln(1-administered)
	drop if LHS == .

	//run regression for each diagnosis charleson combination and save output 
	reg LHS medicaid ib1.proc_id
	
	est save `"$output/medicaid_treat_pattern/coefficients.ster"', append 
	est save `"$output/medicaid_treat_pattern/coefficients_`d'.ster"', replace  
 
	use `"$output/medicaid_treat_pattern/coefficients.dta"', clear 
	replace coef = _b[medicaid] if dx_charl == "`d'"
	replace stdr = _se[medicaid] if dx_charl == "`d'"
			
	save `"$output/medicaid_treat_pattern/coefficients.dta"', replace 


}

********************************************************************************
********************************************************************************
********************** Main Model Table for Appendix (Table A4) ****************
********************************************************************************
********************************************************************************

cap mkdir `"$output/model_estimation"'

clear all 
eststo clear 

//load the tau estimates for Medicaid 
est use `"$output/model_estimation/parameters/taurf_Medicaid.ster"'
eststo taurf_caid

est use `"$output/model_estimation/parameters/tau_Medicaid_pooledreasons.ster"'
eststo tau_caid_pr

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_allgroups.ster"'
eststo tau_caid_byr_ag 
gen total_caid_all_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_smallgroups.ster"'
eststo tau_caid_byr_sg 

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_largegroups.ster"'
eststo tau_caid_byr_lg

//load the tau estimates for Medicare 
est use `"$output/model_estimation/parameters/taurf_Medicare.ster"'
eststo taurf_care

est use `"$output/model_estimation/parameters/tau_Medicare_pooledreasons.ster"'
eststo tau_care_pr

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_allgroups.ster"'
eststo tau_care_byr_ag 

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_smallgroups.ster"'
eststo tau_care_byr_sg 

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_largegroups.ster"'
eststo tau_care_byr_lg

//load the tau estimates for Commercial 
est use `"$output/model_estimation/parameters/taurf_Commercial.ster"'
eststo taurf_com

est use `"$output/model_estimation/parameters/tau_Commercial_pooledreasons.ster"'
eststo tau_com_pr

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_allgroups.ster"'
eststo tau_com_byr_ag 

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_smallgroups.ster"'
eststo tau_com_byr_sg 

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_largegroups.ster"'
eststo tau_com_byr_lg

//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

		#delimit ;
		esttab taurf_caid tau_caid_pr tau_caid_byr_ag tau_caid_byr_sg tau_caid_byr_lg
			   taurf_care tau_care_pr tau_care_byr_ag tau_care_byr_sg tau_care_byr_lg 
			   taurf_com tau_com_pr tau_com_byr_ag tau_com_byr_sg tau_com_byr_lg
			   using "table5_row1.tex", replace substitute(_ \_)
		nonumbers se b(3) se(4) noobs nonotes nostar
		mtitles("\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group.}" "\shortstack{Large \\ group.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group}" "\shortstack{Large \\ group}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group}" "\shortstack{Large \\ group}") booktabs mgroups("Medicaid" "Medicare" "Commercial", pattern(1 0 0 0 0 1 0 0 0 0 1 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) keep(_cons) 
		coeflabels(_cons "Average $\tau$");
		
		#delimit cr

eststo clear 


cd "..\..\..\code\main_article"

//load the CIP estimates for Medicaid 
est use `"$output/model_estimation/parameters/lost_revenue_Medicaid.ster"'
eststo lr_caid

est use `"$output/model_estimation/parameters/CIP_Medicaid_pooledreasons.ster"'
eststo CIP_caid_pr

est use `"$output/model_estimation/parameters/CIP_Medicaid_byreasons_allgroups.ster"'
eststo CIP_caid_byr_ag 

est use `"$output/model_estimation/parameters/CIP_Medicaid_byreasons_smallgroups.ster"'
eststo CIP_caid_byr_sg 

est use `"$output/model_estimation/parameters/CIP_Medicaid_byreasons_largegroups.ster"'
eststo CIP_caid_byr_lg

//load the CIP estimates for Medicare 
est use `"$output/model_estimation/parameters/lost_revenue_Medicare.ster"'
eststo lr_care

est use `"$output/model_estimation/parameters/CIP_Medicare_pooledreasons.ster"'
eststo CIP_care_pr

est use `"$output/model_estimation/parameters/CIP_Medicare_byreasons_allgroups.ster"'
eststo CIP_care_byr_ag 

est use `"$output/model_estimation/parameters/CIP_Medicare_byreasons_smallgroups.ster"'
eststo CIP_care_byr_sg 

est use `"$output/model_estimation/parameters/CIP_Medicare_byreasons_largegroups.ster"'
eststo CIP_care_byr_lg

//load the CIP estimates for Commercial 
est use `"$output/model_estimation/parameters/lost_revenue_Commercial.ster"'
eststo lr_com

est use `"$output/model_estimation/parameters/CIP_Commercial_pooledreasons.ster"'
eststo CIP_com_pr

est use `"$output/model_estimation/parameters/CIP_Commercial_byreasons_allgroups.ster"'
eststo CIP_com_byr_ag 

est use `"$output/model_estimation/parameters/CIP_Commercial_byreasons_smallgroups.ster"'
eststo CIP_com_byr_sg 

est use `"$output/model_estimation/parameters/CIP_Commercial_byreasons_largegroups.ster"'
eststo CIP_com_byr_lg

//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

		#delimit ;
		esttab lr_caid CIP_caid_pr CIP_caid_byr_ag CIP_caid_byr_sg CIP_caid_byr_lg
			   lr_care CIP_care_pr CIP_care_byr_ag CIP_care_byr_sg CIP_care_byr_lg 
			   lr_com CIP_com_pr CIP_com_byr_ag CIP_com_byr_sg CIP_com_byr_lg
			   using "table5_row2.tex", replace substitute(_ \_)
		nonumbers se b(2) se(3) nostar noobs nonotes 
		mtitles("\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group.}" "\shortstack{Large \\ group.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group.}" "\shortstack{Large \\ group.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{All \\ phys.}" "\shortstack{Small \\ group.}" "\shortstack{Large \\ group.}") booktabs mgroups("Medicaid" "Medicare" "Commercial", pattern(1 0 0 0 0 1 0 0 0 0 1 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) keep(_cons) 
		coeflabels(_cons "Average CIP");
		
		#delimit cr
		

cd "..\..\..\code\main_article"
		
		
		
		
****************************************************
***************** Row 3 ****************************
****************************************************
		
clear all		
set obs 6000
gen y = 1
gen x = 5
gen z = 2

reg y x z, nocons
eststo placeholder 		
	
gen y1 = 1
gen x1 = 5
gen z1 = 2

reg y1 x1 z1, nocons
eststo placeholder1	


local rename _cons taucoef x1 taucoef


//load Medicaid results for model esimtations, no reason, no size 
use `"$output/model_estimation/estimations_nosize_noreason_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Medicaid_allreasons_allgroups.ster"'
//determine esitmates to be used 
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p99)
keep if pay_type_pooled == 2


//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row3_col2



//load Medicare results for model esimtations, no reason, no size 
use `"$output/model_estimation/estimations_nosize_noreason_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Medicare_allreasons_allgroups.ster"'

//determine esitmates to be used 
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p99)
keep if pay_type_pooled == 1


//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row3_col7


//load Commercial results for model esimtations, no reason, no size 
use `"$output/model_estimation/estimations_nosize_noreason_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Commercial_allreasons_allgroups.ster"'

//determine esitmates to be used 
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p99)
keep if pay_type_pooled == 3


//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row3_col12

//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

local rename _cons taucoef z taucoef
	#delimit;

	esttab placeholder row3_col2 placeholder1 placeholder1 placeholder1 placeholder row3_col7 placeholder1 placeholder1 placeholder1 
	placeholder row3_col12 placeholder1 placeholder1 placeholder1 using "table5_row3.tex", 
	rename(`rename') keep(taucoef) replace 
	coeflabels(taucoef "$\mu^{0}$, all")
	not stats(serror, labels(" ")) nostar b(2) noobs nolines nonumber nomtitles;

	#delimit cr


cd "..\..\..\code\main_article"

	
****************************************************
***************** Row 4 ****************************
****************************************************	
local rename_row4 extra_line taucoef1 z taucoef1

//load Medicaid estimates 
est use `"$output/model_estimation/parameters/model_est_Medicaid_allreasons_allgroups.ster"'
eststo row4_col2

//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Medicare_allreasons_allgroups.ster"'
eststo row4_col7

//load Commercial estimate 
est use `"$output/model_estimation/parameters/model_est_Commercial_allreasons_allgroups.ster"'
eststo row4_col12

//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

	#delimit;

	esttab placeholder row4_col2 placeholder1 placeholder1 placeholder1 placeholder row4_col7 placeholder1 placeholder1 placeholder1 
	placeholder row4_col12 placeholder1 placeholder1 placeholder1 using "table5_row4.tex", 
	rename(`rename_row4') keep(taucoef1) replace nonotes eqlabels(none)
	coeflabels(taucoef1 "$\mu^{1}$, all")
	se nostar b(2) noobs nolines nonumber nomtitles;

	#delimit cr


cd "..\..\..\code\main_article"

	
****************************************************
*********** MODEL ESTIMATES BY REASON **************
****************************************************
local reasons `""administrative" "contractual" "coverage" "duplicate" "information""'
	
foreach r of local reasons {
	
	if "`r'" == "administrative" {
		
		local row = 5
		local linerow = 6
		local tlab "Admin."
	}
	
	else if "`r'" == "contractual" {
		
		local row = 7
		local linerow = 8
		local tlab "Contr."
	}
	
	else if "`r'" == "coverage" {
		
		local row = 9
		local linerow = 10
		local tlab "Cov."
	}
	
	else if "`r'" == "duplicate" {
		
		local row = 11
		local linerow = 12
		local tlab "Dup."
	}
	
	else if "`r'" == "information" {
		
		local row = 13
		local linerow = 14
		local tlab "Info."
	}
****************************************************
************** Row 5, 7, 9, 11, 13 *****************
****************************************************
clear all 

//crate placeholder 		
clear all		
set obs 6000
gen y = 1
gen x = 5
gen z = 2

reg y x z, nocons
eststo placeholder 		

//local for renaming coefficients 
local rename_row _cons taucoef

*****************************************
********* Column 3 
//load Medicaid results for model esimtations, reason, no size 
use `"$output/model_estimation/estimations_nosize_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_allgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 2
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col3


*****************************************
********* Column 4
//load Medicaid results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 1 
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_smallgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 2
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col4

*****************************************
********* Column 5
//load Medicaid results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 2
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_largegroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 2
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col5



*****************************************
********* Column 8
//load Medicare results for model esimtations, reason, no size 
use `"$output/model_estimation/estimations_nosize_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_allgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 1
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col8


*****************************************
********* Column 9
//load Medicare results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 1 
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_smallgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 1
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col9

*****************************************
********* Column 10
//load Medicaid results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 2
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_largegroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 1
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col10



*****************************************
********* Column 13
//load Commercial results for model esimtations, reason, no size 
use `"$output/model_estimation/estimations_nosize_bin.dta"', clear 
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_allgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 3
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col13


*****************************************
********* Column 14
//load Medicaid results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 1 
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_smallgroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 3
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col14

*****************************************
********* Column 15
//load Medicaid results for model esimtations, reason, size 
use `"$output/model_estimation/estimations_bin.dta"', clear 
keep if size_indicator == 2
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_largegroups.ster"'

//determine esitmates to be used 
keep if pay_type_pooled == 3
sum claim_cost_se , d
keep if claim_cost_se > 0 & claim_cost_se<r(p95)
keep if visit_code_cat == "`r'"

//computing the standard errors of the mean coefficient using the delta method
matrix varcov = e(V)
forval x = 1/51 { 
	cap drop cov_`x'
	gen cov_`x' = .
	
	forval y = 1/51 {
	
		replace cov_`x' = varcov[`x', `y'] if state == `y'
}
}

gen sum_tmp = .
forval x = 1/51 {
	
	gegen sum_cov_`x' = sum(cov_`x')
	replace sum_tmp = sum_cov_`x' if _n == `x'
	
}
gegen sum_final = sum(sum_tmp)

di sqrt((sum_final/_N^2))
local stnder = round(sqrt((sum_final/_N^2)),0.01)

di `stnder'

//calculating the mean cofficient 
replace claim_cost = claim_cost*(-1)
reg claim_cost
estadd local serror "(`stnder')"
eststo row`row'_col15


//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'
// tabulate the row 
	#delimit;

	esttab placeholder placeholder row`row'_col3 row`row'_col4 row`row'_col5 placeholder placeholder row`row'_col8 row`row'_col9 row`row'_col10 
	placeholder placeholder row`row'_col13 row`row'_col14 row`row'_col15 using "table5_row`row'.tex", 
	rename(`rename_row') keep(taucoef) 
	coeflabels(taucoef "$\mu^{0}$, `tlab' $\rho$")
	replace 
	not stats(serror, labels(" ")) nostar b(2) noobs nolines nonumber nomtitles;

	#delimit cr


cd "..\..\..\code\main_article"


	
****************************************************
********* Rows 6, 8, 10, 12 and 14 *****************
****************************************************	
local rename_linerow extra_line taucoef1

*****************************************
********* Column 3
//load Medicaid estimates 
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_allgroups.ster"'
eststo row`linerow'_col3

*****************************************
********* Column 4
//load Medicaid estimates 
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_smallgroups.ster"'
eststo row`linerow'_col4

*****************************************
********* Column 5
//load Medicaid estimates 
est use `"$output/model_estimation/parameters/model_est_Medicaid_`r'_largegroups.ster"'
eststo row`linerow'_col5


*****************************************
********* Column 8
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_allgroups.ster"'
eststo row`linerow'_col8

*****************************************
********* Column 9
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_smallgroups.ster"'
eststo row`linerow'_col9

*****************************************
********* Column 10
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Medicare_`r'_largegroups.ster"'
eststo row`linerow'_col10

*****************************************
********* Column 13
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_allgroups.ster"'
eststo row`linerow'_col13

*****************************************
********* Column 14
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_smallgroups.ster"'
eststo row`linerow'_col14

*****************************************
********* Column 15
//load Medicare estimates 
est use `"$output/model_estimation/parameters/model_est_Commercial_`r'_largegroups.ster"'
eststo row`linerow'_col15

//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

	#delimit;

	esttab placeholder placeholder row`linerow'_col3 row`linerow'_col4 row`linerow'_col5 placeholder placeholder row`linerow'_col8 row`linerow'_col9 row`linerow'_col10 placeholder placeholder row`linerow'_col13 row`linerow'_col14 row`linerow'_col15 using "table5_row`linerow'.tex", 
	rename(`rename_linerow') keep(taucoef1) eqlabels(none)
	coeflabels(taucoef1 "$\mu^{1}$, `tlab' $\rho$")
	replace se nostar b(2) noobs nolines nonumber nomtitles nonotes; 
	#delimit cr


cd "..\..\..\code\main_article"

}


***************************************************
************** Rows 15 and 16 *********************
***************************************************
eststo clear 
clear all 
set obs 10 
//placeholder for column 1 
gen placeholder_col_nomodel = 0
estpost tabstat placeholder_col_nomodel
eststo col_nomodelNLL


//load the tau estimates for Medicaid 
est use `"$output/model_estimation/parameters/taurf_Medicaid.ster"'
gen caid_nom_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicaid_pooledreasons.ster"'
gen caid_pr_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_allgroups.ster"'
gen caid_all_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_smallgroups.ster"'
gen caid_small_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicaid_byreasons_largegroups.ster"'
gen caid_large_N = e(N)

//load the tau estimates for Medicare 
est use `"$output/model_estimation/parameters/taurf_Medicare.ster"'
gen care_nom_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicare_pooledreasons.ster"'
gen care_pr_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_allgroups.ster"'
gen care_all_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_smallgroups.ster"'
gen care_small_N = e(N)

est use `"$output/model_estimation/parameters/tau_Medicare_byreasons_largegroups.ster"'
gen care_large_N = e(N)

//load the tau estimates for Commercial 
est use `"$output/model_estimation/parameters/taurf_Commercial.ster"'
gen com_nom_N = e(N)

est use `"$output/model_estimation/parameters/tau_Commercial_pooledreasons.ster"'
gen com_pr_N = e(N)

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_allgroups.ster"'
gen com_all_N = e(N)

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_smallgroups.ster"'
gen com_small_N = e(N)

est use `"$output/model_estimation/parameters/tau_Commercial_byreasons_largegroups.ster"'
gen com_large_N = e(N)



//load the tau estimates for Medicaid -- pooled reason 
est use `"$output/model_estimation/parameters/model_est_Medicaid_allreasons_allgroups.ster"'
gen tau_caid_pr_LL = e(ll)

estpost tabstat caid_nom_N
eststo col1N

estpost tabstat caid_pr_N
eststo col2N

estpost tabstat tau_caid_pr_LL
eststo col2LL

local version `""all" "small" "large""'


//Medicaid Estimations by reason 
foreach v of local version {
	
	//load the tau estimates for Medicaid -- by reason, all groups 
	est use `"$output/model_estimation/parameters/model_est_Medicaid_administrative_`v'groups.ster"'
	gen admin_caid_`v'_LL = e(ll)
	
	est use `"$output/model_estimation/parameters/model_est_Medicaid_contractual_`v'groups.ster"'
	gen contr_caid_`v'_LL = e(ll)
	
	est use `"$output/model_estimation/parameters/model_est_Medicaid_coverage_`v'groups.ster"'
	gen cov_caid_`v'_LL = e(ll)
	
	est use `"$output/model_estimation/parameters/model_est_Medicaid_duplicate_`v'groups.ster"'
	gen dup_caid_`v'_LL = e(ll)
	
	est use `"$output/model_estimation/parameters/model_est_Medicaid_information_`v'groups.ster"'
	gen info_caid_`v'_LL = e(ll)
	
	gen total_caid_`v'_LL = admin_caid_`v'_LL + contr_caid_`v'_LL + cov_caid_`v'_LL + dup_caid_`v'_LL + info_caid_`v'_LL

}
 
estpost tabstat caid_all_N
eststo col3N

estpost tabstat caid_small_N
eststo col4N

estpost tabstat caid_large_N
eststo col5N

estpost tabstat total_caid_all_LL
eststo col3LL

estpost tabstat total_caid_small_LL
eststo col4LL

estpost tabstat total_caid_large_LL
eststo col5LL

//load the tau estimates for Medicare -- pooled reason 
est use `"$output/model_estimation/parameters/model_est_Medicare_allreasons_allgroups.ster"'
gen tau_care_pr_LL = e(ll)
 
estpost tabstat care_nom_N
eststo col6N

estpost tabstat care_pr_N
eststo col7N

estpost tabstat tau_care_pr_LL
eststo col7LL

//Medicare Estimations 
foreach v of local version {
	
	//load the tau estimates for Medicare -- by reason, all groups 
	est use `"$output/model_estimation/parameters/model_est_Medicare_administrative_`v'groups.ster"'
	gen admin_care_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Medicare_contractual_`v'groups.ster"'
	gen contr_care_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Medicare_coverage_`v'groups.ster"'
	gen cov_care_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Medicare_duplicate_`v'groups.ster"'
	gen dup_care_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Medicare_information_`v'groups.ster"'
	gen info_care_`v'_LL = e(ll)

	gen total_care_`v'_LL = admin_care_`v'_LL + contr_care_`v'_LL + cov_care_`v'_LL + dup_care_`v'_LL + info_care_`v'_LL

}
 
estpost tabstat care_all_N
eststo col8N

estpost tabstat care_small_N
eststo col9N

estpost tabstat care_large_N
eststo col10N

estpost tabstat total_care_all_LL
eststo col8LL

estpost tabstat total_care_small_LL
eststo col9LL

estpost tabstat total_care_large_LL
eststo col10LL

//load the tau estimates for Commercial -- pooled reason 
est use `"$output/model_estimation/parameters/model_est_Commercial_allreasons_allgroups.ster"'
gen tau_com_pr_LL = e(ll)

estpost tabstat com_nom_N
eststo col11N

estpost tabstat com_pr_N
eststo col12N

estpost tabstat tau_com_pr_LL
eststo col12LL

//Commercial Estimations 
foreach v of local version {
	
	//load the tau estimates for Commercial -- by reason, all groups 
	est use `"$output/model_estimation/parameters/model_est_Commercial_administrative_`v'groups.ster"'
	gen admin_com_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Commercial_contractual_`v'groups.ster"'
	gen contr_com_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Commercial_coverage_`v'groups.ster"'
	gen cov_com_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Commercial_duplicate_`v'groups.ster"'
	gen dup_com_`v'_LL = e(ll)

	est use `"$output/model_estimation/parameters/model_est_Commercial_information_`v'groups.ster"'
	gen info_com_`v'_LL = e(ll)

	gen total_com_`v'_LL = admin_com_`v'_LL + contr_com_`v'_LL + cov_com_`v'_LL + dup_com_`v'_LL + info_com_`v'_LL

}
 
estpost tabstat com_all_N
eststo col13N

estpost tabstat com_small_N
eststo col14N

estpost tabstat com_large_N
eststo col15N

estpost tabstat total_com_all_LL
eststo col13LL

estpost tabstat total_com_small_LL
eststo col14LL

estpost tabstat total_com_large_LL
eststo col15LL


//set cd to avoid conflict on BEA server 
cd `"$output/model_estimation"'

#delimit ;
	esttab col1N col2N col3N col4N col5N col6N col7N col8N col9N col10N col11N col12N col13N col14N col15N 
			using "table5_row15.tex" , cells("mean(fmt(%20.0fc))") 
	rename(caid_nom_N "Number of visits" caid_pr_N "Number of visits" caid_all_N "Number of visits" caid_small_N "Number of visits" caid_large_N "Number of visits" 
			care_nom_N "Number of visits" care_pr_N "Number of visits" care_all_N "Number of visits" care_small_N "Number of visits" care_large_N "Number of visits"
		   com_nom_N "Number of visits" com_pr_N "Number of visits" com_all_N "Number of visits" com_small_N "Number of visits" com_large_N "Number of visits")
	unstack nonumbers booktabs replace substitute(_ \_) noobs;
#delimit cr


#delimit ;
	esttab col_nomodelNLL col2LL col3LL col4LL col5LL col_nomodelNLL col7LL col8LL col9LL col10LL col_nomodelNLL col12LL col13LL col14LL col15LL 
			using "table5_row16.tex", cells("mean(fmt(%20.0fc))") 
	rename(placeholder_col_nomodel "Log Likelihood" tau_caid_pr_LL "Log Likelihood" total_caid_all_LL "Log Likelihood" total_caid_small_LL "Log Likelihood" total_caid_large_LL "Log Likelihood"
		   tau_care_pr_LL "Log Likelihood" total_care_all_LL "Log Likelihood" total_care_small_LL "Log Likelihood" total_care_large_LL "Log Likelihood"
		   tau_com_pr_LL "Log Likelihood" total_com_all_LL "Log Likelihood" total_com_small_LL "Log Likelihood" total_com_large_LL "Log Likelihood")
	unstack nonumbers booktabs replace substitute(_ \_) noobs;
#delimit cr


cd "..\..\..\code\main_article"



**********************************************************
** Combine the tables into one tables with three panels **
**********************************************************
cap prog drop panelcombine
prog define panelcombine
qui {
syntax, use(str asis) paneltitles(str asis) columncount(integer) save(str asis) [CLEANup]
preserve

tokenize `"`paneltitles'"'
//read in loop
local num 1
while "``num''"~="" {
local panel`num'title="``num''"
local num=`num'+1
}


tokenize `use'
//read in loop
local num 1
while "``num''"~="" {
tempfile temp`num'
insheet using "``num''", clear
save `temp`num''
local max = `num'
local num=`num'+1
}

//conditional processing loop
local num 1
while "``num''"~="" {
local panellabel : word `num' of `c(alpha)'
use `temp`num'', clear
	if `num'==1 { //process first panel -- clip bottom
	drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
	drop if v1=="\end{tabular}" | v1=="}"
	replace v1 = "[1em]" if v1=="\bottomrule" 
	}
	
	else if `num'==14 { //process final panel -- clip top
	//process header to drop everything until first hline
	drop if v1=="\begin{tabular}{l*{15}{c}}"
	replace v1="[0.5em]" if v1=="[1em]"
	replace v1 = "\midrule" if v1=="\end{tabular}"
		}
		
	if `num'==15 { //process first panel -- clip bottom
	g temp = (v1 == "\midrule")
	replace temp = temp+temp[_n-1] if _n>1
	drop if temp==0
	drop temp
	
	drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
	drop if v1=="}" | v1=="\end{tabular}" | v1=="\bottomrule" | v1=="\midrule" 
	}
		
	else if `num'==`max' { //process final panel -- clip top
	//process header to drop everything until first hline
	g temp = (v1 == "\midrule")
	replace temp = temp+temp[_n-1] if _n>1
	drop if temp==0
	drop temp
	drop if v1=="\begin{tabular}{l*{15}{c}}" | v1=="\midrule" 
	replace v1="[0.5em]" if v1=="[1em]"
			}
		
	else if `num'==2 { //process middle panels -- clip top and bottom
	//process header to drop everything until first hline
	g temp = (v1 == "\midrule")
	replace temp = temp+temp[_n-1] if _n>1
	drop if temp==0
	drop temp
	
	drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
	drop if v1=="}" | v1=="\end{tabular}"
	//replace v1="[1em]" if v1=="\end{tabular}"
	drop if v1=="\midrule"
	replace v1 = "\midrule \\" if v1=="\bottomrule"
	}
	
	else if `num'== 3 { //process middle panels -- clip top and bottom
	//process header to drop everything until first hline
	
	// drop if v1=="\begin{tabular}{l*{15}{c}}"
	drop if v1=="\begin{tabular}{l*{15}{c}}"
	drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
	drop if v1=="\end{tabular}" | v1=="}"
	replace v1 = "" if v1=="\bottomrule"
	drop if v1=="\bottomrule"
	drop if v1=="\midrule"
	}

	forval cline = 5(2)13 {
		else if `num'== `cline' { //process middle panels -- clip top and bottom
		//process header to drop everything until first hline
		
		// drop if v1=="\begin{tabular}{l*{15}{c}}"
		replace v1="[1em]" if v1=="\begin{tabular}{l*{15}{c}}"
		drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
		drop if v1=="\end{tabular}" | v1=="}"
		replace v1 = "" if v1=="\bottomrule"
		drop if v1=="\bottomrule"
		drop if v1=="\midrule"
		}
	}
	forval rline = 4(2)12 {
		else if `num'==`rline' { //process middle panels -- clip top and bottom
		//process header to drop everything until first hline
		
		drop if v1=="\begin{tabular}{l*{15}{c}}"
		replace v1="[0.5em]" if v1=="[1em]"
		drop if strpos(v1,"Note:")>0 | strpos(v1,"in parentheses")>0 | strpos(v1,"p<0")>0
		drop if v1=="\end{tabular}" | v1=="}"
		replace v1 = "" if v1=="\bottomrule"
		drop if v1=="\bottomrule"
		drop if v1=="\midrule"
		}
	}
	save `temp`num'', replace
local num=`num'+1
}

use `temp1',clear
local num 2
while "``num''"~="" {
append using `temp`num''
local num=`num'+1
}

outsheet using `save', noname replace noquote


	if "`cleanup'"!="" { //erasure loop
	tokenize `use'
	local num 1
		while "``num''"~="" {
		erase "``num''"
		local num=`num'+1
		}
	}

restore
}
end

cd `"$output/model_estimation"'


panelcombine, use(table5_row1.tex table5_row2.tex table5_row3.tex table5_row4.tex table5_row5.tex table5_row6.tex table5_row7.tex table5_row8.tex table5_row9.tex table5_row10.tex table5_row11.tex table5_row12.tex table5_row13.tex table5_row14.tex table5_row15.tex table5_row16.tex)  columncount(15) paneltitles("") save(`"../paper_inputs/appendix_model_main.tex"') cleanup 


cd "..\..\..\code\main_article"






********************************************************************************
********************************************************************************
********************** MEDICAID ACCEPT SCATTER PLOT ****************************
************************** APPENDIX FIGURE A.1 *********************************
********************************************************************************
********************************************************************************

set scheme uncluttered

clear all
use `"$output/summary_stats/medicaid_accept/SKA_medicaid_accept.dta"'

merge 1:1 payee_state_cd using `"$output/summary_stats/medicaid_accept/IQVIA_medicaid_accept.dta"'

gr tw scatter mean_accept accept_medicaid_myear, mlab(payee_state_cd) || function y = x , range(0 1) yti("SKA Survey Mean Medicaid Acceptance") xti("IQVIA Data Mean Medicaid Acceptance") ylab(0.2(0.2)1) xlab(0.2(0.2)1)

gr export `"$output/paper_inputs/SKA_IQVIA_medicaid_accept.pdf"', replace 
gr export `"$output/paper_inputs/SKA_IQVIA_medicaid_accept.png"', replace 




		
********************************************************************************
********************************************************************************
*********** Table showing the Change in the Accept Decision ********************
************************** APPENDIX Table A.1 **********************************
********************************************************************************
********************************************************************************

clear all

use `"$raw_input/$mover_file_size"', clear

gen accept_medicare = 1 if medicare == "Y"
replace accept_medicare = 0 if medicare == "N"
replace accept_medicare = . if acceptinsurance == . 
bys npimedicare_id: gegen mean_medicare = mean(accept_medicare)
gen capacity = 1 - mean_medicare

xtset npimedicare_id year 
local sampleselect   "(nummoves==1 | nummoves==0) & ( eventtime >=-3 & eventtime <=4 | eventtime == . ) & capacity == 0" 

reg acceptinsurance  L.acceptinsurance if `sampleselect' 
gen delta_accept = acceptinsurance - L.acceptinsurance

gen no_change = 0 
replace no_change = 1 if delta_accept == 0 

gen accept_change = 0 
replace accept_change = 1 if delta_accept == 1

gen noaccept_change = 0 
replace noaccept_change = 1 if delta_accept == -1
keep if `sampleselect' & delta_accept !=.

//move year indicator 
gen moveyear = "Move Year"
replace moveyear = "Non-Move Year" if event_time != 0 

estpost tabstat no_change accept_change noaccept_change, by(moveyear) nototal stat(mean)

#delimit ;
	
	esttab using `"$output/paper_inputs/medicaid_accept_move_year.tex"', cells("no_change(fmt(3)) accept_change(fmt(3)) noaccept_change(fmt(3))") booktabs unstack nonumbers nomtitles replace substitute(_ \_) noobs collabels("\shortstack{Fraction with \\ no Change }" "\shortstack{Fraction Switching to \\ Accept Medicaid}" "\shortstack{Fraction Switching to not \\ Accept Medicaid}");

		   
#delimit cr











*************************************************************
*************************************************************
****** Endogenous Denial -- Medicaid Treatment Pattern ******
******** Appendix Table A.3 and Appendix Figure A.3**********
*************************************************************

set scheme uncluttered

cap mkdir `"$output/medicaid_treat_pattern"'
cap mkdir `"$output/medicaid_treat_pattern/coef_ordered_graph"'
cap mkdir `"$output/medicaid_treat_pattern/pden_ordered_graph"'
cap mkdir `"$output/medicaid_treat_pattern/pdencaid_ordered_graph"'
cap mkdir `"$output/medicaid_treat_pattern/deltap_ordered_graph"'


use `"$output/medicaid_treat_pattern/potential_procs.dta"', clear 
save `"$output/medicaid_treat_pattern/dx_procs_probabilities.dta"', replace 

levelsof dx_charl, local(dx)
clear 
set obs 20

gen coef = .
gen stder = . 
gen dx_charl = ""
gen proc_id = _n
matrix jac = J(20,21,0)


foreach d of local dx {	
	
	replace dx_charl = "`d'"
	
	
	est use  `"$output/medicaid_treat_pattern/coefficients_`d'.ster"'

	mat jac[1,1] =  exp(_b[_cons] + _b[medicaid])/((1 + exp(_b[_cons] + _b[medicaid]))^2)
	mat jac[1,21] = exp(_b[_cons] + _b[medicaid])/((1 + exp(_b[_cons] + _b[medicaid]))^2) - (exp(_b[_cons])/((1 + exp(_b[_cons]))^2))

	replace coef = exp(_b[_cons] + _b[medicaid])/(1 + exp(_b[_cons] + _b[medicaid])) -  exp(_b[_cons])/(1 + exp(_b[_cons])) if _n == 1
		

	forval p = 2/20 {
		
	est use  `"$output/medicaid_treat_pattern/coefficients_`d'.ster"'

	mat jac[`p',1] =  exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id])/((1 + exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id]))^2)
	mat jac[`p',21] = exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id])/((1 + exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id]))^2) - exp(_b[_cons] + _b[`p'.proc_id])/((1 + exp(_b[_cons] + _b[`p'.proc_id]))^2)
	mat jac[`p',`p'] = exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id])/((1 + exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id]))^2) - exp(_b[_cons] + _b[`p'.proc_id])/((1 + exp(_b[_cons] + _b[`p'.proc_id]))^2)


	local coefficient exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id])/(1 + exp(_b[_cons] + _b[medicaid] + _b[`p'.proc_id])) -  exp(_b[_cons] + _b[`p'.proc_id])/(1 + exp(_b[_cons] + _b[`p'.proc_id]))
		
	replace coef = round(`coefficient', 0.00001) if _n == `p'
	

}


est use  `"$output/medicaid_treat_pattern/coefficients_`d'.ster"'

matrix A = e(V)
matselrc A m, row(1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22) col(1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22)
mat list m
mat jact = jac'

mat varcov = jac*m*jact

forval o = 1/20 {
	
	local scalar = varcov[`o',`o']
	
	replace stder = sqrt(`scalar') if _n == `o'
}



save `"$output/medicaid_treat_pattern/coefficients_`d'.dta"', replace 

}


use `"$output/medicaid_treat_pattern/dx_procs_probabilities.dta"', clear
levelsof dx_charl, local(dx)

foreach d of local dx {	
	
	merge 1:1 dx_charl proc_id using `"$output/medicaid_treat_pattern/coefficients_`d'.dta"', update  nogen
	
}

// share significant 
gen conf_int = stder*1.96

gen upper_bound = . 
replace upper_bound = coef + conf_int if coef < 0 
gen ind = 0
replace ind = 1 if upper_bound < 0 & upper_bound != .
gegen sig_negative_n = sum(ind)
gen sig_negative = sig_negative_n/_N
gen sig_negative_ind = 0
replace sig_negative_ind = 1 if ind ==1 

//summary stats for negatively signficiant 
cap drop ind 

gen lower_bound = . 
replace lower_bound = coef - conf_int if coef > 0 
gen ind = 0
replace ind = 1 if lower_bound > 0 & lower_bound != .
gegen sig_positive_n = sum(ind)
gen sig_positive = sig_positive_n/_N
gen sig_positive_ind = 0
replace sig_positive_ind = 1 if ind ==1 

// Correlation between P(administered) and P(denial) -- Table A.3
gen delta_denp = p_denial_medicaid - p_denial

reg coef delta_denp
eststo corr1

esttab corr1 using `"$output/paper_inputs/correlation_intensive.tex"' , ///
replace substitute(_ \_) nonumbers booktabs mtitles("$\Delta$ P(administered)") keep(delta_denp)  /// 
coeflabels(delta_denp "$\Delta$ Denial Probability") se b(4) se(4 ) stats(N r2, fmt(%7.0f %7.5f) labels("\$N\$" "\$R^2\$")) ///
starlevels(* 0.10 ** 0.05 *** 0.01)  label varwidth(20) nonotes


//graph ordered by the denial probabilioty for Medicaid -- Figure A.3(a)
cap drop rank 
sort p_denial_medicaid
gen rank = _n
serrbar coef conf_int rank, mvopts(msize(vtiny)) yline(0) yti("Delta P(administered)") xti("Medicaid Denial Probability (ranked)")
gr export `"$output/paper_inputs/treatment_pattern_95conf_ranked.pdf"', replace 
gr export `"$output/paper_inputs/treatment_pattern_95conf_ranked.png"', replace 




//graph ordered by the difference in the denial probability between commercial/medicare and medicaid -- Figure A.3(b)
cap drop rank
sort delta_denp
gen rank = _n
serrbar coef conf_int  rank, mvopts(msize(vtiny)) yline(0) yti("Delta P(administered)") xti("P(Medicaid Denial) - P(Commercial/Medicare Denial) (ranked)")
gr export `"$output/paper_inputs/treatment_pattern_95conf_rankeddiff.pdf"', replace 
gr export `"$output/paper_inputs/treatment_pattern_95conf_rankeddiff.png"', replace 

	
log close 

